#include "stdafx.h"
#include "CPUClass.h"


CCPUClass::CCPUClass(void) : m_ulLastSampleTime(0), m_lCPUUsage(0)
{
}


CCPUClass::~CCPUClass(void)
{
}

void CCPUClass::Initialize()
{
	PDH_STATUS tStatus;

	m_bCanReadCPU = true;

	tStatus = PdhOpenQuery(NULL, 0, &m_tQueryHandle);
	if(tStatus != ERROR_SUCCESS)
	{
		m_bCanReadCPU = false;
	}

	tStatus = PdhAddCounter(m_tQueryHandle, TEXT("\\Processor(_Total)\\% processor time"), 0, &m_tCounterHandle);
	if(tStatus != ERROR_SUCCESS)
	{
		m_bCanReadCPU = false;
	}

	m_ulLastSampleTime = GetTickCount();

	m_lCPUUsage = 0;
}

void CCPUClass::ShutDown()
{
	if(m_bCanReadCPU == true)
	{
		PdhCloseQuery(m_tQueryHandle);
	}
}

void CCPUClass::Frame()
{
	PDH_FMT_COUNTERVALUE tValue;

	if(m_bCanReadCPU == true)
	{
		if((m_ulLastSampleTime + 1000) < GetTickCount())
		{
			m_ulLastSampleTime = GetTickCount();
			PdhCollectQueryData(m_tQueryHandle);
			PdhGetFormattedCounterValue(m_tCounterHandle, PDH_FMT_LONG, NULL, &tValue);
			m_lCPUUsage = tValue.longValue;
		}
	}
}

int CCPUClass::GetCPUPercentage()
{
	int nUsage = 0;

	if(m_bCanReadCPU == true)
	{
		nUsage = (int)m_lCPUUsage;
	}
	else
	{
		nUsage = 0;
	}

	return nUsage;
}